﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

/// <summary>
/// Summary description for GeraExcel
/// </summary>
/// 

namespace Util
{
    public class GeraExcel : System.Web.UI.Page
    {
        public static void ExportarGridView(Control gv, Page page)
        {
            string attachment = "attachment; filename=NewsLetter.xls";
            page.Response.ClearContent();
            page.Response.AddHeader("content-disposition", attachment);
            page.Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            // Criar um form para conter o Grid
            HtmlForm frm = new HtmlForm();
            gv.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(gv);
            frm.RenderControl(htw);

            //Renderizar o Grid
            page.Response.Write(sw.ToString());
            page.Response.End();

        }

        public static Control PrepararGridView(Control gv)
        {
            LinkButton lb = new LinkButton();
            Literal l = new Literal();
            String name = String.Empty;

            //Os metodos abaixo retiram os controles e deixam só os valores
            for (int i = 0; i < gv.Controls.Count; i++)
            {
                if (gv.Controls[i].GetType() == typeof(LinkButton))
                {
                    l.Text = (gv.Controls[i] as LinkButton).Text;
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }
                else if (gv.Controls[i].GetType() == typeof(DropDownList))
                {
                    l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }
                else if (gv.Controls[i].GetType() == typeof(CheckBox))
                {
                    l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }

                else if (gv.Controls[i].GetType() == typeof(ImageButton))
                {
                    l.Text = (gv.Controls[i] as ImageButton).CommandArgument;
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }

                if (gv.Controls[i].HasControls())
                {
                    PrepararGridView(gv.Controls[i]);
                }
            }

            return gv;
        }
    }
}